<?php
namespace Modules\Social\Traits;

use Illuminate\Support\Facades\Auth;
use Modules\Core\Models\User;
use Modules\Social\Models\UserSocial;

trait HasSocial
{
    /**
     * @param $driver
     * @param $openid
     * @param array $usinfo
     * @param string $oid
     * @return bool|void
     */
    public static function loginWithSocial($driver, $openid, $usinfo = [])
    {
        $socialiteUser = new UserSocial();

        if(!$openid) {
            abort(400, 'openid获取失败');
            return;
        }

        $userData = [
            'name' => isset($usinfo['name'])?$usinfo['name']:'',
            'nickname' =>isset($usinfo['nickname'])?$usinfo['nickname']:'',
            'avatar' => isset($usinfo['avatar'])?$usinfo['avatar']:'',
        ];
        $user = $socialiteUser->getUser($driver, $openid, $userData);

        // Log::debug("driver:$driver, openid: $openid");

        if (!$user) {
            $user = User::create($userData);
            $socialiteUser->create(array_merge($userData, [
                'create_by' => $user->id,
                'token' => isset($usinfo['token'])?$usinfo['token']:'',
                'driver' => $driver,
                'openid' => $openid,
                'avatar' => isset($usinfo['avatar'])?$usinfo['avatar']:'',
                'anonymous_openid' => isset($usinfo['anonymous_openid'])?$usinfo['anonymous_openid']:''
            ]));
        }

//        Auth::logout();
        Auth::loginUsingId($user->id);
        session(['__social' => array_merge([$driver => $user], session('__social')??[])]);
        session()->save();

        return !Auth::guest();
    }
}
